#define KEY1 4
#define KEY2 5
#include <LiquidCrystal_I2C.h>//初始化I2C屏幕
#include <Wire.h>

#define Relay_1 2 //继电器1
#define Relay_2 3 //继电器2


String Lcd1, Lcd2; //初始变量 给后面LCD显示ON和OFF用
int Flag_up = 1;
int comdata;//初始化一个串口变量
int sk;
LiquidCrystal_I2C lcd(0x3F, 16, 2);
void setup()
{

  pinMode(Relay_1, OUTPUT);//设置输出给继电器
  pinMode(Relay_2, OUTPUT);//设置输出给继电器

  pinMode(KEY1, INPUT_PULLUP);
  pinMode(KEY2, INPUT_PULLUP);

  digitalWrite(Relay_1, HIGH);//启动时继电器断电状态
  digitalWrite(Relay_2, HIGH);//启动时继电器断电状态

  Serial.begin(9600);//

  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Switch 1 IS :OFF");
  lcd.setCursor(0, 1);
  lcd.print("Switch 2 IS :OFF");

}

void loop()
{
  //  Serial.print(ScanKey(1));
  sk = ScanKey(1);
  comdata = Serial.read();
  if (sk == 1 || comdata == 49) {
    digitalWrite(Relay_1, !digitalRead(Relay_1));//Relay状态翻转
    if (digitalRead(Relay_1) == LOW)
    {
      Lcd1 = "ON";
    }
    else
    {
      Lcd1 = "OFF";
    }
    lcd.setCursor(13, 0);
    lcd.print("   ");
    lcd.setCursor(13, 0);
    lcd.print(Lcd1);
    delay(100);
  }
  else if (sk == 2 || comdata == 50) {
    digitalWrite(Relay_2, !digitalRead(Relay_2));//Relay状态翻转
    if (digitalRead(Relay_2) == LOW)
    {
      Lcd1 = "ON";
    }
    else
    {
      Lcd1 = "OFF";
    }
    lcd.setCursor(13, 1);
    lcd.print("   ");
    lcd.setCursor(13, 1);
    lcd.print(Lcd1);
    delay(100);
  }
  Serial.println(comdata);
}

unsigned char ScanKey(int mode)     //按键扫描程序，返回键值
{
  /*长按设置
       if(mode)
    {
      Flag_up=1;
      }
  */
  if (Flag_up  && (digitalRead(KEY1) == LOW || digitalRead(KEY2) == LOW ) )  //当Flag_up = 1并且按键按下时
  {
    Flag_up = 0;                    //清空Flag_up
    delay(30);                      //延时去抖动
    if (digitalRead(KEY1) == LOW)     //按键按下
    {
      return 1;                     //返回键值1
    }
    if (digitalRead(KEY2) == LOW)     //按键按下
    {
      return 2;                     //返回键值2
    }
  }
  if (digitalRead(KEY1) == HIGH && digitalRead(KEY2) == HIGH)    //按键松开时候
  {
    Flag_up = 1;                    //置位Flag_up
  }
  return 0;                         //返回键值0
}
